/**
 * 
 */
package org.compiere.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;

import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.Env;

/**
 * @author V.Sokolov
 *
 */
public class MBPMVersionBudget extends X_BPM_VersionBudget {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 7327769826133151517L;
	
	/**	Static Logger	*/
	private static CLogger	s_log	= CLogger.getCLogger (MBPMVersionBudget.class);

	/**
	 * @param ctx
	 */
	public MBPMVersionBudget(Properties ctx) {
		super(ctx);
	}

	/**
	 * @param ctx
	 * @param BPM_VersionBudget_ID
	 * @param trxName
	 */
	public MBPMVersionBudget(Properties ctx, int BPM_VersionBudget_ID,
			String trxName) {
		super(ctx, BPM_VersionBudget_ID, trxName);
	}

	/**
	 * @param ctx
	 * @param rs
	 * @param trxName
	 */
	public MBPMVersionBudget(Properties ctx, ResultSet rs, String trxName) {
		super(ctx, rs, trxName);
	}
	
	/* 
	 */
	@Override
	protected boolean afterSave(boolean newRecord, boolean success) {
		
		X_BPM_VersionBudgetLine verLine = null;
		
		if(newRecord && success){
			verLine = new X_BPM_VersionBudgetLine(getCtx(),0,get_TrxName());
			verLine.setBPM_VersionBudget_ID(get_ID());
			verLine.setBPM_VersionType(X_BPM_VersionBudgetLine.BPM_VERSIONTYPE_Current);
			verLine.setBPM_Version(MRefList.getListName(getCtx(), X_BPM_VersionBudgetLine.BPM_VERSIONTYPE_AD_Reference_ID, X_BPM_VersionBudgetLine.BPM_VERSIONTYPE_Current));
			verLine.saveEx();
			
			//--Делаем поиск предыдущей версии для того чтобы скопировать настройки форм линий ячеек
//			setAD_Org_ID(0);
//			int prevBPM_VersionBudget_ID = 0;
//			prevBPM_VersionBudget_ID = DB.getSQLValue(null, "SELECT MAX(BPM_VersionBudget_ID) FROM BPM_VersionBudget WHERE IsActive='Y'");
//			List<MBPMFormCode> formCodesList = new ArrayList<MBPMFormCode>();
//			for(MBPMFormCode formCode : MBPMVersionBudget.getFormCodes(prevBPM_VersionBudget_ID))
//			{
//				MBPMFormCode newFormCode = new MBPMFormCode(getCtx(), 0, get_TrxName());
//				copyValues(formCode, newFormCode);
//				newFormCode.set_Value("BPM_VersionBudget_ID", get_ID());
//				newFormCode.saveEx();
//				formCodesList.add(newFormCode);
//				for(MBPMFormColumn formColumn : formCode.getColumns(getCtx(), formCode.get_ID(), get_TrxName()))
//				{
//					MBPMFormColumn newFormColumn = new MBPMFormColumn(getCtx(), 0, get_TrxName());
//					copyValues(formColumn, newFormColumn);
//					newFormColumn.setBPM_FormCode_ID(newFormCode.get_ID());
//					newFormColumn.saveEx();
//				}
//			}
//
//			
//			for(MBPMForm form:MBPMForm.getForms(prevBPM_VersionBudget_ID, getAD_Org_ID()))
//			{
//				MBPMForm newForm = new MBPMForm(getCtx(), 0, get_TrxName());
//				newForm.setAD_Client_ID(getAD_Client_ID());
//				newForm.setAD_Org_ID(form.getAD_Org_ID());
//				newForm.setBPM_VersionBudget_ID(get_ID());
//				newForm.set_Value("BPM_Subs_ID", form.get_Value("BPM_Subs_ID"));
//				newForm.setName(form.getName());
//				newForm.setTabLevel(form.getTabLevel());
//				newForm.setWebParam1(form.getWebParam1());
//				newForm.setWebParam2(form.getWebParam2());
//				newForm.setWebParam3(form.getWebParam3());
//				newForm.setWebParam4(form.getWebParam4());
//				newForm.setWebParam5(form.getWebParam5());
//				newForm.set_Value("Line", form.get_Value("Line"));
//				newForm.setIsOrderBy(form.isOrderBy());
//				int newFormCode_ID = 0;
//				for(int i=0; i< formCodesList.size();i++)
//				{
//					if(form.getName().equals(formCodesList.get(i).getName()))
//					{
//						newFormCode_ID = formCodesList.get(i).getBPM_FormCode_ID();
//						formCodesList.remove(i);
//						break;
//					}
//				}
//				if(newFormCode_ID > 0)
//					newForm.setBPM_FormCode_ID(newFormCode_ID);
//				else
//					newForm.setBPM_FormCode_ID(form.getBPM_FormCode_ID());
//				newForm.saveEx();
//				
//				for(MBPMFormLine formLine : MBPMForm.getLines(getCtx(), form.get_ID(), get_TrxName()))
//				{
//					MBPMFormLine newFormLine = new MBPMFormLine(getCtx(), 0, get_TrxName());
//					copyValues(formLine, newFormLine);
//					newFormLine.setBPM_Form_ID(newForm.get_ID());
//					newFormLine.saveEx();
//					
////					for(MBPMFormCell formCell : formLine.getLines(getCtx(), formLine.get_ID(), get_TrxName()))
////					{
////						MBPMFormCell newCell = new MBPMFormCell(getCtx(), 0, get_TrxName());
////						copyValues(formCell, newCell);
////						newCell.setBPM_FormLine_ID(newFormLine.get_ID());
////						newCell.saveEx();
////					}
//				}
//			}
			//--
		}

		return success;
	}
	
	/* Find the active version of the budget */
	public static X_BPM_VersionBudget getVersionBudget(){
		
		X_BPM_VersionBudget budget = new X_BPM_VersionBudget(Env.getCtx(), 0, null);
    	PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		// The current budget
		String sql_ = "select * from bpm_versionBudget where isActive='Y'";
		
		try
		{
			pstmt = DB.prepareStatement(sql_,null);
			rs = pstmt.executeQuery();
			if(rs.next())
				budget = new X_BPM_VersionBudget(Env.getCtx(), rs, null);		
		}
		catch (SQLException e)
		{
			s_log.log(Level.INFO, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
		
		return budget;
	}
	
	/* Find the active version of the budget into the current branch */
	public static int getCurrentVersion(){
		
		int current = 0;
    	PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		// The current version of the budget
		String sql_ = "select r.bpm_versionbudgetline_id from bpm_versionBudget t \n" +
				"join bpm_versionbudgetline r on r.bpm_versionBudget_id=t.bpm_versionBudget_id \n" +
				"where t.isActive='Y' and r.bpm_versionType='"+X_BPM_VersionBudgetLine.BPM_VERSIONTYPE_Current+"'";
		
		try
		{
			pstmt = DB.prepareStatement(sql_,null);
			rs = pstmt.executeQuery();
			if(rs.next())
				current = rs.getInt(1);			
		}
		catch (SQLException e)
		{
			s_log.log(Level.INFO, "product", e);
		}
		finally
		{
			DB.close(rs, pstmt);
			rs = null; pstmt = null;
		}
		
		return current;
	}
	
    public static MBPMFormCode[] getFormCodes(int BPM_VersionBudget_ID)
    {
    	List<MBPMFormCode> list = null;
    	list = new Query(Env.getCtx(), I_BPM_FormCode.Table_Name, "BPM_VersionBudget_ID = ?", null)
    					.setParameters(BPM_VersionBudget_ID)
    					.setOnlyActiveRecords(true)
    					.setOrderBy(I_BPM_FormCode.COLUMNNAME_BPM_FormCode_ID)
    					.list();
    	return list.toArray(new MBPMFormCode[list.size()]);
    }
}
